import router from './router';
import store from './store';
import NProgress from 'nprogress'; // progress bar
import AuthUtils from 'src/api/auth'; // getToken from cookie

NProgress.configure({ showSpinner: false });// NProgress Configuration

const whiteList = ['/login', '/authredirect', '/404', '/401'];// no redirect whitelist

// 必须要提前生成菜单的页面
const menuList = ['/a'];

router.beforeEach((to, from, next) => {
    NProgress.start(); // start progress bar
    // 检查登陆状态，确认token是否失效, 白名单有时也要获取登陆信息
    let loginStatus = AuthUtils.checkLogin();
    let pass = false;
    // 跳转至登陆页面
    let redirect = '/login';
    // 以免登录白名单开头的页面都不需要权限，直接进入, 但是如果有登陆信息就获取用户信息
    if (whiteList.some(path => to.path.startsWith(path)) || loginStatus) {
        pass = true;
    }
    if (pass) {

        // 没有权限菜单的，生成权限菜单之后再进入
        if (menuList.some(path => to.path.startsWith(path))
            && store.state.permission.addRouters.length <= 0) {

            store.dispatch('generateRoutes')
                .then(() => { // 根据roles权限生成可访问的路由表
                    next({ ...to, replace: true }); // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                })
                .catch(() => {
                    alert('登陆信息已失效');
                    next(redirect);
                });
        } else {
            next();
        }
    } else {
        alert('登陆信息已失效');
        next(redirect);
    }
});

router.afterEach(() => {
    NProgress.done(); // finish progress bar
});
